/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ejb;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import jpa.CredenzialiUtente;
import jpa.Studente;

/**
 *
 * @author admin
 */
@Stateless
public class GestoreStudente implements GestoreStudenteLocal {
    
    @PersistenceContext
    private EntityManager em;

    public Studente login(String user, String pass) {
        CredenzialiUtente cs = em.find(CredenzialiUtente.class, user);
        if(cs != null){
           String hashword = null;
           try {
               MessageDigest md5 = MessageDigest.getInstance("MD5");
               md5.update(pass.getBytes());
               BigInteger hash = new BigInteger(1, md5.digest());
               hashword = hash.toString(16);
           }catch (NoSuchAlgorithmException nsae) {
                // ignore
           }
           if(cs.getPassword().equals(hashword)){
               Studente s= em.find(Studente.class, cs.getStudenteid());
               return s;
           }
        }
        return null;

    }

    public boolean registra(CredenzialiUtente cs, Studente s) {
        CredenzialiUtente c = controllaUsername(cs);
        if(c != null) {
            return false;
        }
        em.persist(s);
        em.flush();
        cs.setStudenteid(s.getId());
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(cs.getPassword().getBytes());
            BigInteger hash = new BigInteger(1, md5.digest());
            cs.setPassword(hash.toString(16));
        }catch (NoSuchAlgorithmException nsae) {
                // ignore
        }
        em.persist(cs);
        return true;
    }

    public CredenzialiUtente controllaUsername (CredenzialiUtente cs){
        return em.find(CredenzialiUtente.class, cs.getUsername());
    }



    


 
}
